import { LoginForm, ApiResponse, Token } from '@/types/data'
import { RootThunkAction, LoginAction } from '@/types/store';
import request from '@/utils/request';
import { setToken, removeToken } from '@/utils/storage'

// 保存token
export function saveToken(token: Token): LoginAction {
  // 存储到本地
  setToken(token)
  return {
    type: 'login/login',
    payload: token
  }
}

// 登录
export function login(values: LoginForm): RootThunkAction {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', values)
    dispatch(saveToken(res.data.data))
    // dispatch({
    //   type: 'login/login',
    //   payload: res.data.data
    // })
    // // 存储到本地
    // setToken(res.data.data)
  }
}

// 获取验证码
export function getCode(mobile: string) {
  return async () => {
    await request.get(`sms/codes/${mobile}`)
  }
}

// 登出
export function logout(): LoginAction {
  // 清除token
  removeToken()
  return {
    type: 'login/logout'
  }
}